package com.iqiyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iqiyi.common.R;
import com.iqiyi.domain.User;
import com.iqiyi.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @auther Z_zjl
 * @date 2022/12/17 12:55
 * @Description
 */
@RestController
@CrossOrigin(value = "http://localhost:8080")
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册
     * 这里他没有把第二次输入的密码传过来验证，那就需要在前端验证了
     * 有待商榷。
     * **/
    @PostMapping("/register")
    public boolean register(@RequestBody User user){
        boolean isSave = userService.save(user);
        if (isSave)return true; //注册成功;
        else return false;      //注册失败;
    }

    /**登录**/
    @PostMapping("/login")
    public User login(@RequestBody User user, HttpServletRequest request){
        //TODO 1判断有无此用户
        LambdaQueryWrapper<User> userWrapper = Wrappers.lambdaQuery();
        userWrapper.eq(User::getName,user.getName())
                   .eq(User::getPassword,user.getPassword());
        User existUser = userService.getOne(userWrapper);
        //TODO 2、有，进行登录
        if (existUser != null){
            // TODO 3.将该用户保存到session中
            HttpSession session = request.getSession();
            session.setAttribute("userInfo", existUser);
            return existUser;
        }else {
            //TODO 4、没有，返回null
            return null;
        }
    }
}
